package com.example.wuqujingdianphone.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wuqujingdianphone.R;
import com.example.wuqujingdianphone.api.GlobalConfig;
import com.example.wuqujingdianphone.base.BaseActivity;
import com.example.wuqujingdianphone.bean.LOginNewBean;
import com.example.wuqujingdianphone.bean.LoginBean;
import com.example.wuqujingdianphone.utils.Message1Event;
import com.example.wuqujingdianphone.utils.NiceDialogUtils;
import com.example.wuqujingdianphone.utils.SPUtil;
import com.example.wuqujingdianphone.utils.StringUtils;
import com.example.wuqujingdianphone.utils.ToastUtil;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;

    @BindView(R.id.edit_phone)
    TextInputEditText mEditPhone;
    @BindView(R.id.textInputLayoutPhone)
    TextInputLayout mTextInputLayoutPhone;

    @BindView(R.id.edit_password)
    TextInputEditText mEditPassword;
    @BindView(R.id.textInputLayoutPassword)
    TextInputLayout mTextInputLayoutPassword;

    @BindView(R.id.btn_login)
    Button mBtnLogin;
    @BindView(R.id.checkbox)
    CheckBox mCheckbox;

    //上次按下返回键的系统时间
    private long lastBackTime = 0;
    //当前按下返回键的系统时间
    private long currentBackTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mTitle.setText("登录");

        initView();
    }

    private void initView() {

        mTextInputLayoutPhone.setHint("请输入您的用户名");//setHint();设置提示语
        //textInputLayoutPhone.setCounterEnabled(true);//是否启用计数器
        //mTextInputLayoutPhone.setCounterMaxLength(11);//启用计数器时，最大字数限制（仅仅用做显示）
        // editPhone.setHintTextColor(ContextCompat.getColor(this, R.color.white));
       /* mEditPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //这儿判断操作，如果输入错误可以给用户提示
                if (s.length() > 11) {
                    mTextInputLayoutPhone.setError("您的手机号不能大于11位");
                } else {
                    mTextInputLayoutPhone.setErrorEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }

        });*/
        mTextInputLayoutPassword.setHint("请输入密码");//setHint();设置提示语
        //textInputLayoutPassword.setCounterEnabled(true);//是否启用计数器

        // mTextInputLayoutPassword.setPasswordVisibilityToggleEnabled(true);//控制密码可见开关是否启用。默认true
        //mTextInputLayoutPassword.setPasswordVisibilityToggleDrawable(R.drawable.ic_visibility_grey);//设置密码可见开关的图标
        //textInputLayoutPassword.setPasswordVisibilityToggleTintList();//控制密码可见开关图标的颜色


        boolean isRememberPassword = SPUtil.getBoolean(LoginActivity.this, "isRememberPassword", false);
        if (isRememberPassword) {
            mCheckbox.setChecked(true);
        }

        strPhone = SPUtil.getString(LoginActivity.this, GlobalConfig.ACCOUNT_KEY, "");
        Log.i(TAG, "initView: strPhone=" + strPhone);
        if (!TextUtils.isEmpty(strPhone)) {
            mEditPhone.setText(strPhone);
        }
        strPassword = SPUtil.getString(LoginActivity.this, "password", "");
        Log.i(TAG, "initView: strPassword=" + strPassword);
        if (!TextUtils.isEmpty(strPassword)) {
            mEditPassword.setText(strPassword);
        }


        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLegal()) {

                    if (mCheckbox.isChecked()) {
                        SPUtil.putBoolean(LoginActivity.this, "isRememberPassword", true);
                        SPUtil.putString(LoginActivity.this, GlobalConfig.ACCOUNT_KEY, strPhone);
                        SPUtil.putString(LoginActivity.this, "password", strPassword);
                    } else {
                        SPUtil.putBoolean(LoginActivity.this, "isRememberPassword", false);
                        SPUtil.putString(LoginActivity.this, GlobalConfig.ACCOUNT_KEY, "");
                        SPUtil.putString(LoginActivity.this, "password", "");
                    }


                    phoneLogin(strPhone, strPassword);
                }
            }
        });


    }


    private String strPhone = "";
    private String strPassword = "";

    public boolean isLegal() {
        strPhone = mEditPhone.getText().toString().trim();
        strPassword = mEditPassword.getText().toString().trim();
        if (StringUtils.isNullOrEmpty(strPhone) || StringUtils.isNullOrEmpty(strPassword)) {
            ToastUtil.showToast("用户名或密码不能为空");
            return false;
        }
      /*  if (!StringUtils.mobileFormat(strPhone)) {
            ToastUtil.showToast("手机号格式不正确");
            return false;
        }
        if (strPassword.length() < 6) {
            ToastUtil.showToast("密码位数不能低于6位");
            return false;
        }*/
        /*if (!StringUtils.isRightPwd(strPassword)) {
            ToastUtil.showToast("密码应为数字和字母格式");
            return false;
        }*/
        return true;
    }


    private void phoneLogin(final String strPhone, final String strPassword) {
        Log.i(TAG, "phoneLogin: strPhone= " + strPhone + " strPassword=" + strPassword);
        showLoading(this);

        //http://wenqujingdian.com/index.php/Jiekou/logintj 
        ViseHttp.GET("index.php/jiekou/MemberSignin")
                .tag(TAG)
                .addParam("memberAccount", strPhone)
                .addParam("memberPass", strPassword)
                .request(new ACallback<LOginNewBean>() {
                    @Override
                    public void onSuccess(LOginNewBean loginBean) {
                        cancelLoading();
                        //Log.i(TAG, "onSuccess: loginBean=" + loginBean);
                        if (loginBean != null) {
                            if (loginBean.isResult()) {
                                ToastUtil.showToast("登录成功");

                                SPUtil.putString(LoginActivity.this, GlobalConfig.ACCOUNT_KEY, strPhone);
                                //SPUtil.putString(LoginActivity.this, "password", strPassword);
                                SPUtil.putString(LoginActivity.this, GlobalConfig.MEMBERTYPE,
                                        loginBean.getData().getMemberType());
                                SPUtil.putBoolean(LoginActivity.this, "isLogin", true);
                                EventBus.getDefault().post(new Message1Event(1, GlobalConfig.LOGIN_IS_OK));
                                finish();


                            } else {
                                ToastUtil.showToast(loginBean.getMsg());
                            }
                        } else {

                        }


                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        cancelLoading();
                        //请求失败，errCode为错误码，errMsg为错误描述
                        ToastUtil.showToast("errCode=" + errCode + " errMsg=" + errMsg);
                    }
                });


    }


    @Override
    public void onBackPressed() {
        finish();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMsgEvent(Message1Event messageEvent) {
        String msg = messageEvent.getMsg();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
